package org.jaaksi.demo.ptr.ui;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.View;
import android.widget.Toast;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.log.LoggerInterceptor;
import okhttp3.*;
import org.jaaksi.demo.ptr.R;
import org.jaaksi.demo.ptr.adapter.SimpleCallBack;
import org.jaaksi.demo.ptr.bean.house.HouseResponse;
import org.jaaksi.demo.ptr.util.ModuleCallback;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * Created by Fcy on 2016/3/17.<br/>
 */
public class OkHttpFinalActivity extends FragmentActivity {
	private OkHttpClient httpClient;
	private Request.Builder requestBuild;

	private String url = "https://app.api.lianjia.com/newhouse/apisearch?city_id=110000";

	public static void goTo(Context context) {
		Intent intent = new Intent(context, OkHttpFinalActivity.class);
		context.startActivity(intent);
	}

	@Override
	protected void onCreate(@Nullable Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_okhttpfinal);


		httpClient = new OkHttpClient();

		// OkHttpClient.Builder 是OkHttpClient的辅助类，用来设置超时，cache，debug模式等
		Cache cache = new Cache(getCacheDir(), 1024 * 1024 * 100);
		try {
			cache.initialize();
		} catch (IOException e) {
			e.printStackTrace();
		}
		OkHttpClient.Builder builder = httpClient.newBuilder()
			.connectTimeout(30000, TimeUnit.MILLISECONDS)
			.readTimeout(30000, TimeUnit.MILLISECONDS)
			.cache(cache)
			.addInterceptor(new LoggerInterceptor("fcy", true));

		// Request.Builder 是Request的辅助类，用来设置请求header,方式,body,tag
		requestBuild = new Request.Builder();
		// 添加通用的请求头
		requestBuild.addHeader("token", "123456");
	}

	public void send(View view) {
		// 为什么不把url放到get(url)不是方便？
		OkHttpUtils.get().url(url).tag(this).build().execute(
			new ModuleCallback<HouseResponse>(HouseResponse.class) {

				/**
				 * 认为404是error。看一下Callback源码什么时候回调
				 * @param call
				 * @param e 服务器404,网络异常、无法连接服务器等
				 */
				@Override
				public void onError(Call call, Exception e) {
					super.onError(call, e);
				}

				/**
				 * 服务器响应code>= 200 <300 看一下Callback源码什么时候回调
				 * @param response 解析失败，返回null
				 */
				@Override
				public void onResponse(HouseResponse response) {
					if (response != null && response.errno == 0 && response.data != null) {

						String result = response.data.resblock_list.list.get(0).toString();
						Log.i("fcy", "----------------- result=" + result);
					}
				}
			});
	}

	public void sendPost(View view) {
		Request request = requestBuild.get().url(url).build();
		// A call is a request that has been prepared for execution，it cannot be executed twice
		Call call = httpClient.newCall(request);
		//请求加入调度
		call.enqueue(new SimpleCallBack<HouseResponse>(HouseResponse.class) {
			@Override
			public void onResponse(Call call, HouseResponse response, int errorCode) {
				if (errorCode == SUCCESS) {
					Log.i("fcy", "----------------- response=" + response.data.resblock_list.list.get(0).toString());
				} else if (errorCode == ERROR_NET) {
					runOnUiThread(new Runnable() {
						@Override
						public void run() {
							Toast.makeText(OkHttpFinalActivity.this, "网络异常", Toast.LENGTH_SHORT).show();
						}
					});

				}
			}
		});
	}
}
